package cn.edu.hzw.criminalintent

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.room.Room
import cn.edu.hzw.criminalintent.bean.Crime
import cn.edu.hzw.criminalintent.database.CrimeDatabase
import cn.edu.hzw.criminalintent.database.migration_1_2
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.lang.IllegalStateException
import java.util.*
import java.util.concurrent.Executors

/**
 * 仓库类
 * 使用仓库模式访问数据库
 */
private const val DATABASE_NAME = "crime-database"
class CrimeRepository private constructor(context:Context){
    private val database:CrimeDatabase = Room.databaseBuilder(
        /**
         * Context对象，数据库用来访问文件系统
         */
        context.applicationContext,
        /**
         * Room用来创建数据库的类
         */
        CrimeDatabase::class.java,
        /**
         * Room将要创建的数据库文件的名字
         */
        DATABASE_NAME
    )
        /**
         * 把Migration添加给Room
         */
        .addMigrations(migration_1_2).build()
    private val crimeDao = database.crimeDao()
    private val executor = Executors.newSingleThreadExecutor()

    /**
     * 定位照片文件
     */
    private val filesDir = context.applicationContext.filesDir
    /**
     * 从CrimeRepository返回LivData
     */
    fun getCrimes(): LiveData<List<Crime>> = crimeDao.getCrimes()

    fun getCrime(id:UUID):LiveData<Crime?> = crimeDao.getCrime(id)

    /**
     * 数据更新
     */
    fun updateCrime(crime: Crime){
        executor.execute {
            crimeDao.updateCrime(crime)
        }
    }

    /**
     * 数据添加
     */
    fun addCrime(crime: Crime) {
        GlobalScope.launch {
            crimeDao.addCrime(crime)
        }
    }
    fun getPhotoFile(crime: Crime):File = File(filesDir,crime.photoFileName)


    companion object{
        private var INSTANCE: CrimeRepository? = null
        fun initialize(context: Context){
            if (INSTANCE == null){
                INSTANCE = CrimeRepository(context)
            }
        }
        fun get(): CrimeRepository{
            return INSTANCE?:
            throw IllegalStateException("CrimeRepository must be initialized")
        }
    }
}